package com.sinai.mshab.server;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.sinai.mshab.client.util.User;
import com.sinai.mshab.client.pages.Login;
import com.sinai.mshab.client.services.Service;
import com.sinai.mshab.client.services.ServiceAsync;
import com.sinai.mshab.client.ui.aggregate.FormData;
import com.sinai.mshab.client.ui.aggregate.PageContainer;
import com.sinai.mshab.client.ui.basic.Warning;

/**
 * This class will attempt to look up the username and password provided to it
 * in the database under the table name 'users'.
 * 
 * It will inform the LoginPage if it is successful.
 * 
 * @author serge
 * 
 */
public class DefaultUserValidator implements UserValidator {

	public void authenticate(String username, String password) {

		ServiceAsync formsService = (ServiceAsync) GWT.create(Service.class);
		ServiceDefTarget target = (ServiceDefTarget) formsService;
		String relativeUrl = GWT.getModuleBaseURL() + FormData.getServletUrl();
		target.setServiceEntryPoint(relativeUrl);
		formsService.validateLogin(username, password, new LoginCallBack());
	}

	public class LoginCallBack implements AsyncCallback {
		public void onFailure(Throwable caught) {
			GWT.log("Error ", caught);
			caught.printStackTrace();
			new Warning(caught.getMessage() + "  " + caught.toString(), 300,
					100);

		}

		// take action based on success of login attempt
		public void onSuccess(Object result) {

			if (result == null) {
				System.out.println("bad username/pass");
				new Warning("The username and password provided is incorrect.",
						300, 100);
				return;
			} else {
				User user = (User) result;

				// login successful
				Cookies.removeCookie("updb cookie");
				Date today = new Date();
				Date expire_date = new Date(today.getTime() + 1000 * 60 * 60
						* 10);
				Cookies.setCookie(FormData.getServletUrl() + " cookie", user
						.getPermission(), expire_date);
				System.out.println("Login page making cookie with permission "
						+ user.getPermission());

				// if pending.exists load pending, else
				if (PageContainer.hasPendingPage()) {
					String pending_page = PageContainer.getPending_page();
					History.newItem(pending_page);
				} else {
					Login.userIsValid();
				}
			}
		}
	}
}
